package org.bw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.bw.entity.Center;
import org.bw.entity.Movie;
import org.bw.mapper.CenterMapper;
import org.bw.mapper.MovieMapper;
import org.bw.service.IMovieService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.ranges.RangeException;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hy.wu
 * @since 2022-07-12
 */
@Service
@Transactional(rollbackFor = {RuntimeException.class})
public class MovieServiceImpl extends ServiceImpl<MovieMapper, Movie> implements IMovieService {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    CenterMapper centerMapper;

    @Override
    public List<Movie> selectMovie() {
        return baseMapper.selectMovie();
    }

    //es同步更新数据
    @Override
    public void saveOrUpdateEs(Movie movie) {
        if (movie.getId()!=null){
            QueryWrapper<Center> wrapper = new QueryWrapper<>();
            wrapper.eq("mid",movie.getId());
            centerMapper.delete(wrapper);
        }
        saveOrUpdate(movie);
        for (Integer directId : movie.getDirectIds()) {
            Center center = new Center();
            center.setDid(directId);
            center.setMid(movie.getId());
            centerMapper.insert(center);
        }
        for (Integer actorId : movie.getActorIds()) {
            Center center = new Center();
            center.setAid(actorId);
            center.setMid(movie.getId());
            centerMapper.insert(center);
        }
        Movie m=baseMapper.selectMovieById(movie.getId());
        IndexQuery indexQuery=new IndexQueryBuilder()
                .withId(m.getId().toString())
                .withObject(m)
                .build();
        elasticsearchRestTemplate.index(indexQuery);
        elasticsearchRestTemplate.refresh(Movie.class);
    }

    @Override
    public void deleteById(int id) {
        removeById(id);
        QueryWrapper<Center> wrapper = new QueryWrapper<>();
        wrapper.eq("mid",id);
        centerMapper.delete(wrapper);
        Movie m=baseMapper.selectMovieById(id);
        IndexQuery indexQuery=new IndexQueryBuilder()
                .withId(m.getId().toString())
                .withObject(m)
                .build();
        elasticsearchRestTemplate.index(indexQuery);
        elasticsearchRestTemplate.refresh(Movie.class);
    }
}
